package com.nageoffer.shortlink.admin.common.interceptor;

import com.alibaba.fastjson2.JSON;
import com.nageoffer.shortlink.admin.common.context.UserContext;
import com.nageoffer.shortlink.admin.common.convention.exception.ServiceException;
import com.nageoffer.shortlink.admin.pojo.entity.UserInfo;
import com.nageoffer.shortlink.admin.toolkit.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        //1.拦截请求

        //2. 提取原始的token
        String token = request.getHeader("token");
        //3. 判断token是否为空，若为空，则返回错误信息401状态码
        if(token == null || token.isEmpty()){
            log.info("令牌为空，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new ServiceException("token为空");
        }
        //4.若是存在校验token是否正确
        try{
            Claims claims = JwtUtil.parseToken(token);
            String userInfoJson = (String) claims.get("userInfo");
            UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
            UserContext.setUser(userInfo);
        }catch (Exception e) {
            log.info("令牌非法，响应401状态码");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new ServiceException("token非法，校验不合格");
        }

        return true;


    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.removeUser();
    }

}
